package com.ruoyi.manage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.manage.config.WxApiConfig;
import com.ruoyi.manage.service.IWxSendMessageService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: wwy
 * @Date: 2021/1/25 9:50
 */
@Service
public class WxSendMessageServiceImpl implements IWxSendMessageService {
    private static final Logger LOGGER = LoggerFactory.getLogger(WxSendMessageServiceImpl.class);
    private static String accessToken;
    @Autowired
    private RestTemplate restTemplate;
    /**
     * 获取accessToken
     */
    public void getAccessToken(){
        String appId = DictUtils.getDictValue("wx_config", "app_id", "");
        String appSecret = DictUtils.getDictValue("wx_config", "app_secret", "");
        String url = WxApiConfig.ACCESS_TOKEN;
        String param = "grant_type=client_credential&"+"appid="+appId+"&secret="+appSecret;
        String responseAccessToken = HttpUtils.sendGet(url, param);
        if(StringUtils.isEmpty(responseAccessToken)){
            throw new CustomException("系统内部错误", HttpStatus.ERROR);
        }
        Map<String,Object> map = JSONObject.parseObject(responseAccessToken, Map.class);

        Object accessTokenObj = map.get("access_token");
        if(accessTokenObj == null){
            throw new CustomException("系统内部错误",HttpStatus.ERROR);
        }
        accessToken = String.valueOf(accessTokenObj);
    }

    public boolean sendWxMessage(String openId,String templateId,String page,Map<String,Object> data){
        if(StringUtils.isEmpty(accessToken)){
            this.getAccessToken();
        }
        LOGGER.info("微信推送发送参数{}",data);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        Map<String,Object> requestMap = new HashMap<>();
        requestMap.put("touser",openId);
        requestMap.put("template_id",templateId);
        if(StringUtils.isNotEmpty(page)){
            requestMap.put("page",page);
        }
        requestMap.put("data",data);
        String param = JSONObject.toJSONString(requestMap);
        HttpEntity httpEntity = new HttpEntity(param,httpHeaders);
        String url = WxApiConfig.SEND_MESSAGE+"?access_token="+accessToken;
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        String body = stringResponseEntity.getBody();
        if(StringUtils.isEmpty(body)){
            throw new CustomException("系统内部错误", HttpStatus.ERROR);
        }
        Map responseBodyMap = JSONObject.parseObject(body, Map.class);
        LOGGER.info("微信推送发送结果{}",body);
        Object errCode = responseBodyMap.get("errcode");
        if(errCode != null){
            if((int)errCode == 0){
                //成功
                return true;
            }
        }
        return false;
    }
}
